#!/usr/bin/ruby
=begin
Rouge Engine v1.0
Ruby-based roguelike game engine.
created by zb (CC0)
=end

require 'curses'
require 'yaml'

# local includes
require_relative 'screen'
require_relative 'world'
require_relative 'thing'
require_relative 'creature'
require_relative 'map'
require_relative 'message'

include Curses

# misc. functions
def loadgame
  $player = YAML::load File.read("data/player.dat")
  $currentmap = YAML::load File.read("data/currentmap.dat")
end
def savegame
  $currentmap.save
  currentmap = YAML::dump($currentmap)
  player = YAML::dump($player)
  File.open("data/currentmap.dat", 'w') do |f|
    f.write(currentmap)
  end
  File.open("data/player.dat", 'w') do |f|
    f.write(player)
  end
end

# set game state
gameover = false

# init world
world = World.new

# check for saved game
if File.exists?("data/player.dat")
  loadgame
else
  # init player and currentmap
  print "Enter your name: "
  name = gets
  $player = Creature.new(name.chomp, '@', 2)
  $currentmap = Map.new(6, 21)
end

# init other stuff
$screen = Screen.new
$msgbox = Message.new

$msgbox.say("Welcome to the game, #{$player.getname}!")
$msgbox.say("Press h, j, k, l to move around.")
$msgbox.say("Press q to quit, n for noclip")

# main loop
until gameover do
  $screen.refresh
  $screen.draw

  # check player status
  if $player.dead?
    gameover = true
  end
  if $player.turn?
    # handle input
    case getch
      when 'q' # quit
        savegame
        $msgbox.say("You quit the game.")
        gameover = true
      when 'k' # up
        $player.move(0,-1)
      when 'j' # down
        $player.move(0,1)
      when 'h' # left
        $player.move(-1,0)
      when 'l' # right
        $player.move(1,0)
      when 't' # teleport
        rx = rand($map_width)
        ry = rand($map_height)
        $player.warp(rx, ry)
        $msgbox.say "You teleported!"
      when 'f' # attack player
        $player.hit($player)
      when 'n' # toggle noclip
        if $player.noclip? == false
          $player.noclip(true)
          $msgbox.say("Noclip enabled.")
        else
          $player.noclip(false)
          $msgbox.say("Noclip disabled.")
        end
      when 'o'
        $player.opendoor
      when 'c'
        $player.closedoor
      when '.'
        $player.endturn
      else
        # do nothing
        $msgbox.say("Invalid command.")
    end
    if $player.gethp < 1
      $msgbox.say("You are dead.")
      $player.kill
    end
  else
    $player.beginturn
  end
# do stuff after turn is over
end

getch

# exit
$screen.close